$(function(){
	var win = window;
	var doc = document;
	var util = win.util = {};
	var server = win.server = {};
	var handler = win.handler = {};
	var render = win.render = {};

	//图片类型
	var uploadImgType = win.uploadImgType = {
		especially:"f9",
		interaction:"f9",
		scenic:"f9"
	};

	//图片的Dom
	var uploadImgDom = win.uploadImgDom = [];



	//富文本编辑器
	var editor;
	util.textEditor=function(){
		KindEditor.ready(function(K) {
	        editor = K.create($("#innerContent"), {
	            resizeType : 1,
	            width  : "100%" ,
	            height :"410px" ,
	            allowPreviewEmoticons : false,
	            allowImageUpload : false,
	            items : [
	                'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
	                'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
	                'insertunorderedlist', '|', 'emoticons', 'image', 'link']
	        });
	    });
	}

	//点击转换形态
	handler.changeTag=function(){
    	$('#choose span').on('click',function(){
    		var _that=$(this);
    		var flag=0;
			$('#selecteds span').each(function(i,list){
    			if(parseInt($(this).attr('goodsTag'))==parseInt(_that.attr('goodsTag'))){
    				++flag;
    			}
    		})
			if(flag==0){
				$(this).clone().appendTo('#selecteds');
    			$(this).addClass('btn-inverse');
			}
    	})

    	$('#selecteds').delegate('span','click',function(){
    		var _that=$(this);
    		$('#choose span').each(function(i,list){
    			if(parseInt($(this).attr('goodsTag'))==parseInt(_that.attr('goodsTag'))){
    				_that.remove();
    				$(this).removeClass('btn-inverse').addClass('btn-success');
    			}
    		})
    	})
    }

    
    
    //动态添加图文框
    handler.selectCheckbox=function(){
    	$('.selector').delegate('input','click',function(){
    		var _that=$(this);
    		if(!_that.is(':checked')){
    			//取消勾选后处理的事
    			_that.parents('.changeNum').find('.control-label').each(function(){
    				if(_that.attr("tagName")==$(this).text()){
	    				$(this).parent().remove();
	    			}
    			})
    		}else{
    			//勾选后处理的事
				var controlGroup = $("<div class='control-group'></div>");
				var label = $('<label class="control-label" for="inputEmail"></label>').text(_that.attr("tagName"));
				var controls = $('<div  class="controls sortable" style="margin-left:190px;"></div>');
				var controlsDiv = $('<div style="float:left;margin-left:10px;position:relative;"></div>');

				if(_that.parents('.changeNum').attr('changeNumFlag') == '1'){
					//适合、特点的渲染
					controls.attr('id','especiallyC'+_that.val());
					var falgEventA= $('<a class="btn btn-success" id="'+("especially"+_that.val())+'" style="margin-left: 30px; position: relative; z-index: 1;width:80px;">上传图片</a>');
				}else if(_that.parents('.changeNum').attr('changeNumFlag') == '2'){
					//互动项目的渲染
					controls.attr('id','interactionC'+_that.val());
					var falgEventA= $('<a class="btn btn-success" id="'+("interaction"+_that.val())+'" style="margin-left: 30px; position: relative; z-index: 1;width:80px;">上传图片</a>');
					var falgEventInput = $('<input type="text" placeholder="￥该项目费用，不填表示免费"/>');
				}
				var img = $('<img src="fwaf"style="display:block;width:220px;margin-top:10px;margin-bottom:10px;" class="img-rounded"//>');
				var textarea = $('<textarea></textarea>');
				var strong = $('<strong style="display:block;font-size:25px;position:absolute;top:20px;left:190px;cursor:pointer;">X</strong>');
				

				controlsDiv.append(img);
				controlsDiv.append(textarea);
				controlsDiv.append(strong);
				controls.append(controlsDiv);
				controlGroup.append(label);

				controlGroup.append(falgEventA);
				if(falgEventInput){
					controlGroup.append(falgEventInput);
				}
				

				controlGroup.append(controls);
    			_that.parents('.selector').after(controlGroup);

    			//调用图片上传
    			if(_that.parents('.changeNum').attr('changeNumFlag') == '1'){
    				window.server.strategyFile("especially"+_that.val(),"#especiallyC"+_that.val(),uploadImgType.especially,'1');
    			}else if(_that.parents('.changeNum').attr('changeNumFlag') == '2'){
    				window.server.strategyFile("interaction"+_that.val(),"#interactionC"+_that.val(),uploadImgType.interaction,'2');
    			}

    		}
    	})
    }



    //多个图片的上传
	server.strategyFile=function(uploadBtn,uploadC,Fxx,flag){

  		var uploadButton = $("#"+uploadBtn);
		var iconRoot = $("#uploadImgList") ;
		
		var doUploadButt = iconRoot.find(".upload-butt") ;
		
		iconRoot.find(".cls").on("click",function(){
			$(this).parent().fadeOut();
		}) ;
		
  		var roomImageUploader = new plupload.Uploader({
		    browse_button: uploadBtn ,
		    url:"/jybb-upload/image/upload.do?belongId=&imageCatalog="+Fxx 
		}) ;
  		
  		roomImageUploader.init() ;
		
  		
  		roomImageUploader.bind('FilesAdded', function(up, files){
  			iconRoot.find("ol").empty() ;
			doUploadButt.show() ;
			iconRoot.show("slow") ;

		    plupload.each(files, function(file) {
		         var li = $("<li style='margin-bottom:10px;'></li>").attr("id",file.id).text(file.name + ' ' + plupload.formatSize(file.size)).appendTo(iconRoot.find('ol'));
		        var delSpan = $("<span style='float:right;margin-right:20px;color:red;cursor:pointer;'>X</span>")
		        .appendTo(li)
		        .on("click",function(){
		        	$(this).parent().remove() ;
		        	if(!iconRoot.find("ol > li").size()){
		        		doUploadButt.hide() ;
		        		iconRoot.hide() ;
		        	}
		        }) ;
		    });
		});

  		/*roomImageUploader.bind('Uploa   dProgress', function(up, file) {
            $('#' + file.id + ' > span').text(file.percent);
		});*/
  		
  		roomImageUploader.bind('FileUploaded', function(up, file,result) {
  			var fileId = eval(result.response)[0];
  			$.ajax({
			 	url : "/jybb-upload/image/getImgById.json?imageId=" +fileId ,
			   	type : "GET" ,
			    dataType: "json" ,
			    success:function(data){
			    	console.log(data);
			    	if(flag == "1"){
			    		//适合、特点的渲染
			    		var controlsDiv = $('<div style="float:left;margin-left:10px;position:relative;"></div>');
						var img = $('<img style="display:block;width:220px;height:220px;margin-top:10px;margin-bottom:10px;" class="img-rounded"/>').attr('src',data['result']['imageUrl']);
						var textarea = $('<textarea></textarea>');
						var strong = $('<strong style="display:block;font-size:25px;position:absolute;top:20px;left:190px;cursor:pointer;">X</strong>');

						controlsDiv.append(img);
						controlsDiv.append(textarea);
						controlsDiv.append(strong);
						$(uploadC).append(controlsDiv);
			    	}else if(flag == '2'){
			    		//互动项目
			    		var controlsDiv = $('<div style="float:left;margin-left:10px;position:relative;"></div>');
			    		var input = $('<input type="text" placeholder="￥该项目费用，不填表示免费"/>');
						var img = $('<img style="display:block;width:220px;height:220px;margin-top:10px;margin-bottom:10px;" class="img-rounded"/>').attr('src',data['result']['imageUrl']);
						var textarea = $('<textarea></textarea>');
						var strong = $('<strong style="display:block;font-size:25px;position:absolute;top:20px;left:190px;cursor:pointer;">X</strong>');
						controlsDiv.append(input)
						controlsDiv.append(img);
						controlsDiv.append(textarea);
						controlsDiv.append(strong);
						$(uploadC).append(controlsDiv);
			    	}else if(flag == '3'){
						var controlsDiv = $('<div style="float:left;margin-right:10px;position:relative;margin-top:10px;">');
			    		var input = $('<input type="button" value="设置为头图" class="btn btn-success" />');
						var img = $('<img src="fwaf"style="display:block;width:220px;height:220px;margin-top:10px;margin-bottom:10px;" class="img-rounded"/>').attr('src',data['result']['imageUrl']);
						var strong = $('<strong style="display:block;font-size:25px;position:absolute;top:50px;left:190px;cursor:pointer;">X</strong>');
						controlsDiv.append(input)
						controlsDiv.append(img);
						controlsDiv.append(strong);
						$(uploadC).append(controlsDiv);
		    		}else if(flag == '4'){
		    			var controlsDiv = $('<div style="float:left;margin-right:10px;position:relative;margin-top:10px;">');
						var img = $('<img src="fwaf"style="display:block;width:220px;height:220px;margin-top:10px;margin-bottom:10px;" class="img-rounded"/>').attr('src',data['result']['imageUrl']);
						var strong = $('<strong style="display:block;font-size:25px;position:absolute;top:20px;left:190px;cursor:pointer;">X</strong>');
						controlsDiv.append(img);
						controlsDiv.append(strong);
						$(uploadC).append(controlsDiv);
			    	}
			    	
			    } ,
		        error:function(){
		        	alert("upload file fail") ;
		        }
	 		}) ;
  		
  		});

        roomImageUploader.bind('UploadComplete', function() {
            iconRoot.hide() ;
            alert('上传成功');
        });
  		
  		roomImageUploader.bind('Error', function(up,err) {
		    alert("文件上传发生错误，请重试!") ;
		});
  		
  		uploadButton.on("click",function(){
			
			doUploadButt.on("click",function(){
				
				roomImageUploader.start() ;
				$(this).unbind("click") ;
			}) ;
		
		}) ;
  		
	};





    //适合场景的TAB切换
	$('#tabController button').on('click',function(e){
		e.preventDefault();
		$('#tabView textarea').eq($(this).index()).show().siblings().hide();
	})

	

})

$(function(){
	handler.changeTag()
	handler.selectCheckbox();
	//拖拽插件的调用
	$('.sortable').sortable();

	//上传图片调用规则(1、合适、特点的开头especially+ID    2、互动项目interaction+ID)

	//（按钮的ID名(前缀不加#或.)，上传成功后要生成内容的容器(说白了DIV名字一个)，图片的imageId，渲染的判断）
	//渲染的判断：1:合适、特点 /  2:互动项目/   3:景区图片   4:景区导览图/   
	//例：window.server.strategyFile('especiallyUploadBtn',"#especiallyC",uploadImgType.especially,"1");

	//上传景区图片
	window.server.strategyFile('uploadScenicImgBtn',"#uploadScenicImgC",uploadImgType.scenic,"3");

	//上传景区导览图
	window.server.strategyFile('guiDeImgBtn',"#guiDeImgC",uploadImgType.scenic,"4");

})